package org.alis.rpc.common.util;

import com.google.common.collect.Lists;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.Nullable;
import java.util.List;
import java.util.Map;

/**
 * @author lc
 */
@Component("appContextUtil")
public class AppContextUtil implements ApplicationContextAware {

    @Override
    public void setApplicationContext(@Nullable ApplicationContext applicationContext) throws BeansException {
        ApplicationContextKeeper.setApplicationContext(applicationContext);
    }


    private static boolean containsBean(String name) {
        return getApplicationContext().containsBean(name);
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        return containsBean(name) ? (T) getApplicationContext().getBean(name) : null;
    }


    public static <T> Map<String, T> getBean(Class<T> clazz) {
        return getApplicationContext().getBeansOfType(clazz);
    }

    public static <T> List<T> getSubBeans(Class<T> clazz){
        return Lists.newArrayList(getApplicationContext().getBeansOfType(clazz).values());
    }



    private static ApplicationContext getApplicationContext() {
        return ApplicationContextKeeper.getApplicationContext();
    }



    public static <T> T getBeanByClassType(Class<T> clazz) {
        return AppContextUtil.getApplicationContext().getBean(clazz);
    }

}

final class ApplicationContextKeeper {

    private ApplicationContextKeeper() {
        throw new IllegalStateException("Utility class");
    }

    /**
     * ApplicationContext
     */
    private static ApplicationContext applicationContext;


    public static void setApplicationContext(ApplicationContext applicationContext) {
        ApplicationContextKeeper.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return ApplicationContextKeeper.applicationContext;
    }
}